package com.tiancan.design.gateway.fillter;

import com.tiancan.design.gateway.bean.Result;
import com.tiancan.design.gateway.service.TokenServiceFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/** @author tiancan */
@Component
public class LoginFilter implements GlobalFilter, Ordered {
  private static final String COOKIE_TOKEN_NAME = "login_token";
  @Autowired private TokenServiceFeignClient tokenServiceFeignClient;

  @Override
  public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    ServerHttpRequest request = exchange.getRequest();
    ServerHttpResponse response = exchange.getResponse();
    //  /api/user/register/txx1994@outlook.com/123456789/464013
    String path = request.getPath().toString();
    if (path.contains("register") || path.contains("isRegistered") || path.contains("code")) {
      return chain.filter(exchange);
    }
    if (path.contains("login")) {
      System.out.println("======>>>>>验证账号密码是否符合规则");
      return chain.filter(exchange);
    }
    List<HttpCookie> httpCookies = request.getCookies().get(COOKIE_TOKEN_NAME);
    if (httpCookies == null || httpCookies.size() == 0) {
      response.setStatusCode(HttpStatus.LOCKED);
      DataBuffer wrap = response.bufferFactory().wrap(("抱歉,您尚未登录系统").getBytes());
      return response.writeWith(Mono.just(wrap));
    }
    String token = httpCookies.get(0).getValue();
    Result<String> result = tokenServiceFeignClient.info(token);
    if (result.getResult()) {
      return chain.filter(exchange);
    }
    response.setStatusCode(HttpStatus.LOCKED);
    DataBuffer wrap = response.bufferFactory().wrap((result.getRes()).getBytes());
    return response.writeWith(Mono.just(wrap));
  }

  @Override
  public int getOrder() {
    return 0;
  }
}
